using System.Collections.Generic;

namespace BasecampRestAPI
{
	public class ListMover
	{
		public static ListMover GetInstance(IProject targetProject)
		{
			return new ListMover(targetProject);
		}
		private ListMover(IProject targetProject)
		{
			_targetProject = targetProject;
		}
		private readonly IProject _targetProject;
		private readonly Dictionary<int, IMilestone> _milestoneMap = new Dictionary<int, IMilestone>();

		public IMilestone CopyMilestone(IMilestone sourceMilestone)
		{
			return (sourceMilestone.Project.Id == _targetProject.Id) ?
				sourceMilestone :
				_targetProject.CreateMilestone(sourceMilestone.Title, sourceMilestone.Deadline,
					sourceMilestone.ResponsibleParty, sourceMilestone.WantsNotification);
		}

		public IToDoList CopyToDoList(IToDoList sourceList)
		{
			IMilestone sourceMilestone = sourceList.Milestone;
			IMilestone clonedMilestone = null;
			if (sourceMilestone != null)
			{
				if (!_milestoneMap.ContainsKey(sourceMilestone.Id))
				{
					_milestoneMap[sourceMilestone.Id] = CopyMilestone(sourceMilestone);
				}
				clonedMilestone = _milestoneMap[sourceMilestone.Id];
			}
			IToDoList clone = _targetProject.CreateToDoList(sourceList.Name, sourceList.Description,
				clonedMilestone, sourceList.Private, sourceList.Tracked);
			foreach (IToDoListItem item in sourceList.Items)
			{
				IToDoListItem clonedItem = clone.CreateItem(item.Content, item.ResponsibleParty, true);
				foreach (ITimeEntry timeEntry in item.TimeEntries)
				{
					clonedItem.AddTimeEntry(timeEntry.Person, timeEntry.Date, timeEntry.Hours, timeEntry.Description);
				}
				if (item.Completed)
				{
					clonedItem.Complete();
				}
			}
			return clone;
		}
	}
}
